import * as c from '@/services/consts';
import * as api from '@/services/broadcastIp';
import * as utils from '@/utils/utils';
import { CheckCircleFilled, CloseCircleFilled, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from 'umi';
import { Badge, Button, Popconfirm, Tag, Tooltip } from 'antd';
import React, { useRef, useState } from 'react';
import Form from './Form';
import ReportForm from './ReportForm';

const List: React.FC = (props: any) => {

  const actionRef = useRef<ActionType>();
  const { hasRight } = useModel('useAuthModel');

  const [formOpen, setFormOpen] = useState<boolean>(false);
  const [formReportOpen, setFormReportOpen] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.BroadcastIp | undefined>(undefined);
  
  // const {
  //   reloadGeoipIsps,
  // } = useModel('useGlobalModel', (model) => ({
  //   reloadGeoipIsps: model.reloadGeoipIsps,
  // }));



  
  const handleFormSubmit = async (record: API.BroadcastIp) => {
    console.log(record);
    // return;

    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } 
    else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormOpen(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };
  

  let columns: ProColumns<API.BroadcastIp>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      search: false,
      // valueEnum: {
      //   true: { status: 'Success' },
      //   false: { status: 'Error' },
      // },
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      width:160,
      render: (_, record) => {
        return <>{record.ipUsedCount > 0 && record.ipInUsedCount == 0 ? <Tag color='red'>{record.ip}</Tag> : record.ip}
        </>;
      }
    },
    {
      title: '起始IP',
      dataIndex: 'ipStart',
      width:150,
      search: false,
    },
    {
      title: '结束IP',
      dataIndex: 'ipEnd',
      width:150,
      search: false,
    },
    // {
    //   title: '可用IP',
    //   dataIndex: 'ipEnd',
    //   width:180,
    //   search: false,
    //   render: (_, record) => {
    //     return <>
    //     <div><Tag>起始</Tag>{record.ipStart}</div>
    //     <div><Tag>结束</Tag>{record.ipEnd}</div>
    //     </>
    //   },
    // },
    {
      title: 'IP 可用 / 总数 / 正在使用',
      dataIndex: 'ipCount',
      width:220,
      search: false,
      render: (_, record) => {
        return <>
        <div style={{fontWeight:'bolder'}}>{record.ipCount - record.ipUsedCount} / {record.ipCount} / {record.ipUsedCount > 0 ? record.ipInUsedCount : ' -'}</div>
        {record.ipUsedLastTime ? <div style={{color:'#999'}}>最后操作：{utils.formatDate(record.ipUsedLastTime)}</div> : ''}
        </>;
      },
    },
    {
      title: '可用服务器',
      dataIndex: 'ipCount',
      search: false,
      render: (_, record) => {
        return record.instanceIds?.map((val) => <Tag color='blue'>{val}</Tag>);
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sorter: true,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width:200,
      search: false,
      render: (_, record) => {
        return <>
        <div><Tag>创建</Tag>{utils.formatDate(record.createTime)}</div>
        <div><Tag>更新</Tag>{utils.formatDate(record.updateTime)}</div>
        </>
      },
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 150,
      render: (_, record) => {
        let cmps = [];
        
        if (hasRight('broadcastip_update')) {
          cmps.push(
            <a
              onClick={() => {
                setFormOpen(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('broadcastip_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }
        

        
        if (hasRight('broadcastip_list')) {
          cmps.push(
            <a
              onClick={() => {
                setFormReportOpen(true);
                setCurrent(record);
              }}
            >
              IP信息
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);
  
 
  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        columns={columns}
        search={{
          span: 5,
          collapsed: false,
        }}
        // toolbar={{
        //   multipleLine: true,
        //   menu: {
        //     type: 'tab',
        //     activeKey: listType,
        //     items: [{label:'ISP列表', key:'isp'},{label:'IP列表', key:'ip'}],
        //     onChange: (tabKey) => {
        //       //console.log('tabKey', tabKey);
        //       setListType(tabKey as string);
        //       // actionRef.current?.reset();
        //     },
        //   },
        // }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];

          if (hasRight('broadcastip_create')) {
            toolbarDoms.push(
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormOpen(true);
                  setCurrent(undefined);
                }}
              >
                <PlusOutlined />
                新建
              </Button>
            );
          }

          return toolbarDoms;
        }}
        pagination={{
          defaultPageSize: 50,
          pageSizeOptions: [
            '50',
            '100',
            '200',
            '300',
            '500',
          ],
          hideOnSinglePage: false,
        }}
        request={api.list}
      />
      


      <Form
        open={formOpen}
        current={current}
        onCancel={() => {
          setCurrent(undefined);
          setFormOpen(false);
        }}
        onSubmit={handleFormSubmit}
      />
      <ReportForm
        visible={formReportOpen}
        current={current}
        onCancel={() => {
          setCurrent(undefined);
          setFormReportOpen(false);
        }}
      />

    </PageContainer>
  );
};

export default List;
